package com.orange.lockscreen.nativeView;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orange.lockscreen.R;
import com.orange.lockscreen.common.LockScreenPreferences;
import com.orange.lockscreen.common.LogHelper;
import com.orange.lockscreen.server.LockscreenView.TimeDateViewCallback;

/**
 * 
 * TimeDateView: display time, date, battery status, alarm
 * 
 */
public class TimeDateView extends LinearLayout implements TimeDateViewCallback {
	private static final String	TAG						= "TimeDateView";

	private static final String	ZERO					= "0";
	private static final String	SPACE					= " ";
	// private static final String COLON = ":";
	private static final String	COMMA					= ",";

	private static final int[]	DAYOFWEEK				= {
			R.string.dayOfWeek_Sunday, R.string.dayOfWeek_Monday,
			R.string.dayOfWeek_Tuesday, R.string.dayOfWeek_Wednesday,
			R.string.dayOfWeek_Thursday, R.string.dayOfWeek_Friday,
			R.string.dayOfWeek_Saturday				};

	private static final int[]	MONTHOFYEAR				= {
			R.string.monthOfYear_January, R.string.monthOfYear_February,
			R.string.monthOfYear_March, R.string.monthOfYear_April,
			R.string.monthOfYear_May, R.string.monthOfYear_June,
			R.string.monthOfYear_July, R.string.monthOfYear_August,
			R.string.monthOfYear_September, R.string.monthOfYear_October,
			R.string.monthOfYear_November, R.string.monthOfYear_December };

	private static final String	AM						= "AM";
	private static final String	PM						= "PM";
	// static final String NO_SERVICE = "No service";
	// static final String CONNECT_TO_CHARGER = "Connect to charger";
	// static final String CONNECT_TO_CHARGER_ABBRE = "Charge";
	// static final String CHARGING = "Charging";
	// static final String FULLY_CHARGED = "Fully charged";
	// static final String FULL_DATE = "EEEE, d MMMM";

	private static final int	LOW_BATTERY_THRESHOLD	= 25;
	private static final int	FULL_BATTERY_THRESHOLD	= 100;

	private int					mCurrLevel				= 0;
	private boolean				mBatteryplugged			= true;
	private String				mNextAlarm;

	private boolean				mIs24					= true;

	private TextView			mTextAMPM;
	private TextView			mTextTime;
	private TextView			mTextDate;
	// TextView mTextOperator;
	// TextView mTextNoSimCard;
	// private LinearLayout mChargingLayout;
	private ImageView			mCharginIcon;
	private TextView			mTextCharging1;
	private TextView			mTextCharging2;
	private TextView			mTextCharging3;
	// private LinearLayout mAlarmLayout;
	private ImageView			mAlarmIcon;
	private TextView			mTextAlarm1;
	private TextView			mTextAlarm2;
	private TextView			mTextAlarm3;

	Context						mContext;

	public TimeDateView(Context context, boolean plugged, int level) {
		super(context);
		mContext = context;
		setBatteryInfo(plugged, level);
		inflate();
		mNextAlarm = getNextAlarmFromSettings();
		LogHelper.d(TAG, "### mNextAlarm == null ? " + (null == mNextAlarm)
				+ ", mNextAlarm: " + mNextAlarm);
//		try {
//			//add by gaoge 2012-01-31,for fix bug cause Lockscreen crash
//			if(null != mNextAlarm){
//				mNextAlarm = new String(mNextAlarm.getBytes("utf-8"), Locale.getDefault().getLanguage());
//			} else {
//				mNextAlarm = "";
//			}
//		} catch (UnsupportedEncodingException e) {
//			if (LogHelper.enableDefaultLog) {
//				e.printStackTrace();
//			}
//			
//		}
		
		if (mNextAlarm == null) {
			mNextAlarm = "";
		}
		

		mIs24 = DateFormat.is24HourFormat(context);

		updateAllView();

	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		updateAlarmView();
		super.onWindowFocusChanged(hasWindowFocus);
	}

	@Override
	public void onTelephonyChangedOuter() {
		// updateViewOnTelephonyChange();

	}

	@Override
	public void onTimeChangedOuter() {
		updateViewOnTimeTick();
	}

	@Override
	public void onBatteryChangedOuter(boolean pluged, int level) {
		setBatteryInfo(pluged, level);
		updateViewOnBatteryChange();
	}

	public void setBatteryInfo(boolean plugged, int level) {
		LogHelper.v(TAG, "plugged=" + plugged + ", level=" + level);
		
		mBatteryplugged = plugged;
		mCurrLevel = level;
	}

	protected void inflate() {
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.layout_view_timedate, this, true);

		mTextAMPM = (TextView) findViewById(R.id.AMPM);
		mTextTime = (TextView) findViewById(R.id.TimeWithoutAmPm);
		mTextDate = (TextView) findViewById(R.id.Date);
		// mTextOperator = (TextView) findViewById(R.id.OperatorName);
		// mTextNoSimCard = (TextView) findViewById(R.id.NoSimCard);
		// mChargingLayout = (LinearLayout) findViewById(R.id.charging_layout);
		mCharginIcon = (ImageView) findViewById(R.id.charing_icon);
		mTextCharging1 = (TextView) findViewById(R.id.battery_text_1);
		mTextCharging2 = (TextView) findViewById(R.id.battery_text_2);
		mTextCharging3 = (TextView) findViewById(R.id.battery_text_3);
		// mAlarmLayout = (LinearLayout) findViewById(R.id.alarm_layout);
		mAlarmIcon = (ImageView) findViewById(R.id.alarm_icon);
		mTextAlarm1 = (TextView) findViewById(R.id.alarm_text_1);
		mTextAlarm2 = (TextView) findViewById(R.id.alarm_text_2);
		mTextAlarm3 = (TextView) findViewById(R.id.alarm_text_3);
	}

	private void updateAllView() {
		updateViewOnTimeTick();
		// updateViewOnTelephonyChange();
		updateViewOnBatteryChange();
		updateAlarmView();
	}

	private void updateViewOnTimeTick() {
		FormatTimeDate formatTimeDate = new FormatTimeDate();
		// set Time&Date view
		if (null == formatTimeDate.getAMPM()) {
			mTextAMPM.setVisibility(View.INVISIBLE);
		} else {
			mTextAMPM.setVisibility(View.VISIBLE);
			mTextAMPM.setText(formatTimeDate.getAMPM());
		}

		mTextDate.setText(formatTimeDate.getDay() + COMMA + SPACE
				+ formatTimeDate.getDate() + SPACE + formatTimeDate.getMonth());

		mTextTime
				.setText(DateFormat.format(getTimeFormatPattern(), new Date()));
	}

	private void updateViewOnBatteryChange() {
		if (!LockScreenPreferences.isBatteryStatusEnabled()) {
			mCharginIcon.setVisibility(INVISIBLE);
			mTextCharging1.setVisibility(INVISIBLE);
			mTextCharging2.setVisibility(INVISIBLE);
			mTextCharging3.setVisibility(INVISIBLE);
		} else {
			// set Battery view
			mCharginIcon.setVisibility(VISIBLE);
			mTextCharging2.setVisibility(VISIBLE);
			if (!mBatteryplugged) {
				// int type = mCurrLevel / LOW_BATTERY_THRESHOLD;
				// switch (type) {
				// case 0:
				// mCharginIcon.setImageResource(R.drawable.timedate_battery_0);
				// break;
				// case 1:
				// mCharginIcon.setImageResource(R.drawable.timedate_battery_1);
				// break;
				// case 2:
				// mCharginIcon.setImageResource(R.drawable.timedate_battery_2);
				// break;
				// case 3:
				// mCharginIcon.setImageResource(R.drawable.timedate_battery_3);
				// break;
				// case 4:
				// mCharginIcon.setImageResource(R.drawable.timedate_battery_4);
				// break;
				// }

				// modify by gaoge 2011-07-21
				if (mCurrLevel < 4) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_0_notcon);
				} else if (mCurrLevel >= 4 && mCurrLevel < 14) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_1_notcon);
				} else if (mCurrLevel >= 14 && mCurrLevel < 29) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_2_notcon);
				} else if (mCurrLevel >= 29 && mCurrLevel < 49) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_3_notcon);
				} else if (mCurrLevel >= 49 && mCurrLevel < 69) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_4_notcon);
				} else if (mCurrLevel >= 69 && mCurrLevel < 89) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_5_notcon);
				} else if (mCurrLevel >= 89 && mCurrLevel <= 100) {
					mCharginIcon
							.setImageResource(R.drawable.battery_level_6_notcon);
				}
				if (mCurrLevel >= LOW_BATTERY_THRESHOLD) {
					mTextCharging1.setVisibility(INVISIBLE);
					mTextCharging3.setVisibility(INVISIBLE);

					mTextCharging2.setText(mCurrLevel + "%");
				} else {
					mTextCharging1.setVisibility(VISIBLE);
					mTextCharging3.setVisibility(VISIBLE);

					mTextCharging1.setText(mCurrLevel + "%");
					// mTextCharging2.setText("Connect to");
					// mTextCharging3.setText("charger");
					mTextCharging2.setText(getResources().getString(
							R.string.connect_to_charger_above));
					mTextCharging3.setText(getResources().getString(
							R.string.connect_to_charger_below));
				}
			} else {
				mTextCharging1.setVisibility(VISIBLE);
				mTextCharging3.setVisibility(INVISIBLE);

				if (mCurrLevel >= FULL_BATTERY_THRESHOLD) {
					// mCharginIcon.setImageResource(R.drawable.timedate_battery_full);
					// modify by gaoge 2011-07-20
					mCharginIcon
							.setImageResource(R.drawable.battery_charging_full_connected);
					mTextCharging1.setText(mCurrLevel + "%");
					mTextCharging2.setText(getResources().getString(
							R.string.fully_charged));
				} else {
					mCharginIcon
					// .setImageResource(R.drawable.timedate_battery_charging);
					// modify by gaoge 2011-07-20
							.setImageResource(R.drawable.battery_charging_connected);
					mTextCharging1.setText(mCurrLevel + "%");
					mTextCharging2.setText(getResources().getString(
							R.string.charging));
				}
			}
		}
	}

//	private void updateAlarmView() {
//		if (!LockScreenPreferences.isAlarmStatusEnabled()) {
//			mTextAlarm1.setVisibility(INVISIBLE);
//			mAlarmIcon.setVisibility(INVISIBLE);
//			mTextAlarm2.setVisibility(INVISIBLE);
//			mTextAlarm3.setVisibility(INVISIBLE);
//		} else {
//			ContentResolver contentResolver = getContext().getContentResolver();
//			String nextAlarmTempString = Settings.System.getString(
//					contentResolver, Settings.System.NEXT_ALARM_FORMATTED);
//			LogHelper.d(TAG, "updateAlarmView. mNextAlarm: " + mNextAlarm + ",nextAlarmTempString : " 
//					+ nextAlarmTempString );
//			if (null != mNextAlarm && !mNextAlarm.equals(nextAlarmTempString)) {
//				mNextAlarm = nextAlarmTempString;
////				updateAlarmView();
//				return;
//			}
//
//			// set Alarm view
//			if (TextUtils.isEmpty(mNextAlarm)) {
//				mTextAlarm1.setVisibility(INVISIBLE);
//				mAlarmIcon.setVisibility(INVISIBLE);
//				mTextAlarm2.setVisibility(INVISIBLE);
//				mTextAlarm3.setVisibility(INVISIBLE);
//			} else {
//				mTextAlarm1.setVisibility(INVISIBLE);
//				mAlarmIcon.setVisibility(VISIBLE);
//				mTextAlarm2.setVisibility(VISIBLE);
//				mTextAlarm3.setVisibility(VISIBLE);
//				mAlarmIcon.setImageResource(R.drawable.timedate_alarm);
//				try {
//					String[] temp = LockScreenUtils.spliteNextAlarm(mNextAlarm);
//					LogHelper.i(TAG, "updateAlarmView. nextAlarm: "
//							+ mNextAlarm + " ,temp[0]: " + temp[0]
//							+ " ,temp[1]: " + temp[1]);
//					mTextAlarm2.setText(temp[0]);
//					mTextAlarm3.setText(temp[1]);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}
	
	//modify by gaoge 2011-12-23
	private void updateAlarmView() {
		if (!LockScreenPreferences.isAlarmStatusEnabled()) {
			mTextAlarm1.setVisibility(INVISIBLE);
			mAlarmIcon.setVisibility(INVISIBLE);
			mTextAlarm2.setVisibility(INVISIBLE);
			mTextAlarm3.setVisibility(INVISIBLE);
		} else {
			String nextAlarmTempString = getNextAlarmFromSettings();
			LogHelper.d(TAG, "################### nextAlarmTempString == null ? " + (null == nextAlarmTempString)
					+ ",nextAlarmTempString: " + nextAlarmTempString);
			
			// Disallow null, some device could return null.
			if (nextAlarmTempString == null) {
				nextAlarmTempString = "";
			}
			
			LogHelper.d(TAG, "updateAlarmView. mNextAlarm: " + mNextAlarm + ",nextAlarmTempString : " 
					+ nextAlarmTempString );
			if (null != mNextAlarm && !mNextAlarm.equals(nextAlarmTempString)) {
				mNextAlarm = nextAlarmTempString;
//				updateAlarmView();
				return;
			}

			// set Alarm view
			if (TextUtils.isEmpty(mNextAlarm)) {
				mTextAlarm1.setVisibility(INVISIBLE);
				mAlarmIcon.setVisibility(INVISIBLE);
				mTextAlarm2.setVisibility(INVISIBLE);
				mTextAlarm3.setVisibility(INVISIBLE);
			} else {
				mTextAlarm1.setVisibility(INVISIBLE);
				mAlarmIcon.setVisibility(VISIBLE);
				mTextAlarm2.setVisibility(VISIBLE);
				mTextAlarm3.setVisibility(VISIBLE);
				mAlarmIcon.setImageResource(R.drawable.timedate_alarm);
				mTextAlarm2.setText(mNextAlarm);
				} 
			}
	}

	private String getNextAlarmFromSettings() {
		return Settings.System.getString(
				getContext().getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED);
	}

	// private String formatNextAlarm(String alarm, String timeFormat) {
	// String nextAlarm;
	// if (timeFormat.equals(TIME_FORMAT_DEFAULT)) {
	// nextAlarm = alarm;
	// } else {
	// int spaceIndex = alarm.indexOf(SPACE);
	// int colonIndex = alarm.indexOf(COLON);
	// int length = alarm.length();
	// String weekday = alarm.substring(0, spaceIndex);
	// String minute = alarm.substring(colonIndex + 1, length);
	// String firstHour = alarm.substring(colonIndex - 2, colonIndex - 1);
	// String lastHour = alarm.substring(colonIndex - 1, colonIndex);
	//
	// if (firstHour != null && firstHour.equals(SPACE)) {
	// firstHour = ZERO;
	// }
	//
	// StringBuffer stringBuffer = new StringBuffer();
	// stringBuffer.append(weekday);
	// stringBuffer.append(SPACE);
	// stringBuffer.append(firstHour);
	// stringBuffer.append(lastHour);
	// stringBuffer.append(COLON);
	// stringBuffer.append(minute);
	//
	// nextAlarm = stringBuffer.toString();
	// }
	//
	// return nextAlarm;
	// }

	private String getTimeFormatPattern() {
		SimpleDateFormat sdf = (SimpleDateFormat) DateFormat
				.getTimeFormat(mContext);
		String oldPattern = sdf.toPattern();
		StringBuilder stringBuilder = new StringBuilder();
		String hourFormat = null;

		if (mIs24) {
			hourFormat = "k";
		} else {
			hourFormat = "h";
		}

		if (oldPattern.contains("HH") || oldPattern.contains("hh")
				|| oldPattern.contains("KK") || oldPattern.contains("kk")) {
			stringBuilder.append(hourFormat + hourFormat + ":");
		} else if (oldPattern.contains("H") || oldPattern.contains("h")) {
			stringBuilder.append(hourFormat + ":");
		}

		if (oldPattern.contains("mm")) {
			stringBuilder.append("mm");
		} else {
			stringBuilder.append("m");
		}

		return stringBuilder.toString();
	}

	class FormatTimeDate {
		private CharSequence	monthView	= null;
		private CharSequence	dayView		= null;
		private CharSequence	dateView	= null;
		private CharSequence	hourView	= null;
		private CharSequence	minView		= null;
		private CharSequence	AMPM		= null;

		public FormatTimeDate() {

			int day = 0;
			int month = 0;
			int date = 0;
			int hour = 0;
			int minute = 0;

			Boolean timeIsOkay = false;
			do {
				Date now = new Date(System.currentTimeMillis());
				day = now.getDay();
				month = now.getMonth();
				date = now.getDate();
				hour = now.getHours();
				minute = now.getMinutes();
				timeIsOkay = (0 <= day && day <= 6)
						&& (0 <= month && month <= 11)
						&& (1 <= date && date <= 31)
						&& (0 <= hour && hour <= 23)
						&& (0 <= minute && minute <= 59);
			} while (!timeIsOkay);

			dayView = getResources().getString(DAYOFWEEK[day]);
			monthView = getResources().getString(MONTHOFYEAR[month]);
			dateView = String.valueOf(date);
			if (!mIs24) {
				if (hour < 12) {
					if (hour == 0)
						hour = 12;
					AMPM = AM;
					hourView = String.valueOf(hour);
				} else {
					hour -= 12;
					if (hour == 0)
						hour = 12;
					AMPM = PM;
					hourView = String.valueOf(hour);
				}
			} else {
				if (hour < 10) {
					hourView = ZERO + hour;
				} else {
					hourView = String.valueOf(hour);
				}
				AMPM = null;
			}

			if (minute < 10)
				minView = ZERO + minute;
			else
				minView = String.valueOf(minute);
		}

		public CharSequence getMonth() {
			return monthView;
		}

		public CharSequence getDay() {
			return dayView;
		}

		public CharSequence getDate() {
			return dateView;
		}

		public CharSequence getHour() {
			return hourView;
		}

		public CharSequence getMinute() {
			return minView;
		}

		public CharSequence getAMPM() {
			return AMPM;
		}
	}

}
